import React, { Component } from "react";
import ProForm, { ProFormDatePicker, ProFormText, ProFormSelect, ProFormTextArea } from "@ant-design/pro-form";
import MusicAPI from '@/services/ant-design-pro/music';
import { message, Space, Image, Button, Input, Modal } from 'antd'
import { ArrowRightOutlined } from '@ant-design/icons';
import { connect } from 'dva'

import UploadImg from '@/components/UploadImg'
import m_config from '@/config/config'
import No_head from '@/assets/image/no_head.jpg'
import Upload from './UploadMusic/uploadMuisc'

import './edit.less'

const { updateMusic, cancelUpload, findMusicLyricList, addMusicLyric, updateMusicLyric } = MusicAPI

@connect(({ music }) => ({
    music
}))
class Edit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            musicData: undefined,
            imgFile: undefined,
            isUploading: false,
            lyric: undefined,
            lyric_id: 0,
            childrenDrawer: false
        }
    }

    updateMusicLyric = async (lyricArea) => {
        const { lyric_id, lyric, music_name, lyric_file_name } = this.props.initData;
        let l_id = -1;
        if (lyricArea == "") {
            message.warning("歌词不能为空");
            return false
        } else if (lyric === lyricArea && lyricArea != "") {
            console.log("未修改歌词");
            return false
        } else {
            if (lyric_id == 0 || lyric_id == null) {
                let result = await addMusicLyric({
                    lyric: lyricArea,
                    lyric_name: music_name
                })
                if (result.status == 'ok') {
                    message.success("添加成功");
                    this.setState({
                        lyric_id: result.data.value.lyric_id
                    })
                    l_id = result.data.value.lyric_id
                } else {
                    message.error('添加失败');
                    console.log(result.data.error);
                }
            } else {
                let result = await updateMusicLyric({
                    lyric: lyricArea,
                    lyric_file_name,
                    lyric_id: lyric_id
                })
                if (result.status == 'ok') {
                    message.success("修改成功");
                    l_id = lyric_id
                } else {
                    message.error('修改失败');
                    console.log(result.data.error);
                }
            }
            this.setState({
                lyric: lyricArea,
                childrenDrawer: false
            });
        }

        return l_id;
    }

    isCanUpload = (params) => {
        this.setState({
            isUploading: false
        })
    }

    onUploadChange = (params) => {
        if (params.status === true) { // 上传状态
            this.setState({ // 开始上传...
                isUploading: true
            })
        }
        if (params.percent >= 100) {
            console.log("上传完成");
            this.setState({
                musicData: params.value
            })
        }
    }

    setImageFile = (params) => {
        this.setState({
            imgFile: params
        })
    }


    async componentDidUpdate(prevProps) {
        const { visible } = this.props;
        const { lyric_id, musicData } = this.state;
        if (visible === false && musicData !== undefined) {
            console.log("取消上传");
            cancelUpload();
        }
        if (visible === false && lyric_id !== 0) { //如果已经添加歌词 并且 还未通过提交按钮提交
            this.handleSubmit()
        }
    }

    /**
     * 修改
     * @param {obj} params 参数
     * @returns 
     */
    handleSubmit = async (params) => {

        const { isShowModal, actionRef, setUserData, initData } = this.props;
        let { musicData, imgFile } = this.state;
        let i = 0, lyric_id;
        if (musicData === undefined && imgFile === undefined) { // 图片文件 与 音频文件判断
            for (let key in params) {
                if (params[key] == initData[key]) {
                    i++;
                }
            }
            if (i >= 7)
                return message.error("您还未修改数据")
        }
        console.log(params);
        if (params.lyric) {
            lyric_id = await this.updateMusicLyric(params.lyric);
            delete params.lyric;
        }
        let data = {
            data: {
                // ...initData,
                ...params,
                lyric_id,
                music_id: initData.music_id,
                music_cover_name: initData.music_cover_name,
                music_cover_src: initData.music_cover_src,
                music_name: params && params.music_name ? params.music_name : musicData && musicData.music_name,
                music_file_name: initData.music_file_name,
                music_file_src: initData.music_file_src,
            },
            _imgfile: imgFile || null,
            _filename: musicData === undefined ? null : musicData.dirname
        }

        this.setState({
            lyric_id: 0,
            lyric: undefined
        })

        let result = await updateMusic(data);
        if (result.status == 'ok') {
            await setUserData();
            actionRef.current.reload();
            message.success("修改成功");
            isShowModal(false);
        } else {
            message.error('修改失败：' + result.data.message);
            console.log(result.data.error);
        }
    }

    async getLyric(lyric_id) {
        let result = await findMusicLyricList({
            lyric_id
        })
        this.setState({
            lyric: result.data.value[0].lyric
        })
    }

    // componentDidMount() {
    //     const { lyric_id } = this.props.initData;
    //     if (lyric_id != 0) {
    //         console.log(lyric_id);
    //         this.getLyric(lyric_id);
    //     }
    // }
    render() {
        const { initData, visible, isShowModal } = this.props;
        const { isUploading, lyric } = this.state;
        const { AlbumSelect, LyricAuthorSelect, MelodyAuthorSelect, SingerSelect } = this.props.music;

        return (
            <Modal
                title="修改音乐"
                width="1110px"
                height="593px"
                footer={false} placement="right"
                visible={visible}
                onCancel={() => isShowModal(false)}
                destroyOnClose={true}
            >
                {initData && <ProForm
                    onFinish={(values) => this.handleSubmit(values)}
                    initialValues={initData}
                    submitter={{
                        // 配置按钮文本
                        searchConfig: {
                            resetText: '重置',
                            submitText: '提交',
                        },
                        render: (props, doms) => {
                            return [
                                <Button key="rest" disabled={isUploading ? true : ""} onClick={() => props.form?.resetFields()}>
                                    重置
                                </Button>,
                                <Button type="primary" disabled={isUploading ? true : ""} key="submit" onClick={() => props.form?.submit?.()}>
                                    提交
                                </Button>,
                            ];
                        },
                    }}
                >
                    <div className="editmodel-left">
                        <ProForm.Group>
                            <Space size={12}>
                                <Image
                                    width={150}
                                    src={initData && initData.music_cover_name ? m_config.local + initData.music_cover_src + initData.music_cover_name : No_head}
                                    onError={(e) => {
                                        e.target.src = No_head;
                                    }}
                                />
                                <ArrowRightOutlined />
                                <UploadImg setImgFile={(values) => this.setImageFile(values)} />
                            </Space>
                            <ProFormText
                                name="music_name"
                                label="音乐名称"
                                placeholder="请输入名称"
                            />
                        </ProForm.Group>

                        <ProForm.Group>
                            <ProFormSelect
                                options={SingerSelect}
                                showSearch
                                style={{ width: 200 }}
                                width="xs"
                                name="singer_id"
                                label="歌手"
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            />
                            <ProFormSelect
                                options={LyricAuthorSelect}
                                showSearch
                                style={{ width: 200 }}
                                width="xs"
                                name="lyric_author_id"
                                label="词作家"
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            />
                            <ProFormSelect
                                options={MelodyAuthorSelect}
                                showSearch
                                style={{ width: 200 }}
                                width="xs"
                                name="melody_author_id"
                                label="曲作家"
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            />
                            <ProFormSelect
                                options={AlbumSelect}
                                showSearch
                                style={{ width: 200 }}
                                width="xs"
                                name="album_id"
                                label="专辑"
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                            />
                        </ProForm.Group>
                        <div>
                            <h4>原音乐文件</h4>
                            <Space>
                                <audio src={initData && m_config.local + initData.music_file_src + initData.music_file_name} controls ></audio>
                            </Space>
                            <Upload isCanUpload={this.isCanUpload} onUploadChange={this.onUploadChange} />
                        </div>

                        <ProFormDatePicker width="md" name="music_issue_time" label="发行时间" />
                    </div>
                    <div className="editmodel-right">
                        <div
                            className="editmodel-area">
                            <ProFormTextArea
                                width="100%"
                                name="lyric"
                                label="歌词"
                            />
                        </div>
                    </div>
                </ProForm >}
            </Modal>
        );
    }
}

export default Edit;